/*
 * File Name: SyncAppAction.java
 * Created on: 
 */

package co.edu.uniandes.intercon.client.action;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.swing.JFrame;

import co.edu.uniandes.intercon.core.model.BaseDto;
import co.edu.uniandes.intercon.core.model.EMessageType;
import co.edu.uniandes.intercon.core.model.P2PMessage;
import co.edu.uniandes.intercon.core.model.RemoteApplicationList;
import co.edu.uniandes.intercon.server.core.Constants;
import co.edu.uniandes.intercon.server.core.P2PException;
import co.edu.uniandes.intercon.server.networking.TCPSender;

/**
 * Action used to sync a peer to an existing server
 * 
 * @author Fabian Gutierrez [fagossa@gmail.com]
 */
public class SyncAppAction extends AbstractBaseGUIAction {

	/**
	 * @see AbstractBaseGUIAction#execute(Map)
	 */
	public Object execute(Map<String, Object> params) throws RuntimeException {
		JFrame window = (JFrame) params.get("window");
		String host = (String) params.get("host");
		
		P2PMessage message = new P2PMessage(null, EMessageType.SYNC);
		
		try {
			Object response = TCPSender.send(message, host, Constants.TCP_PORT);
			if (response != null) {
				addRemoteApplications(response);
			}
		} catch (P2PException ex) {
			if (ex.getCause() != null && (ex.getCause() instanceof IOException)) {
				throw new P2PException(
						"Error al sincronizar con el destino solicitado");
			} else {
				throw ex;
			}
		}
		return null;
	}

	/*
	 * adds remote applications to the local's remote application list
	 */
	private void addRemoteApplications(Object response) {
		if (response instanceof P2PMessage) {
			List<BaseDto> responseArray = (List<BaseDto>)((P2PMessage) response).getResponse();
			RemoteApplicationList.getInstance().clear();
			if (responseArray != null) {
				for (BaseDto applicationDto : responseArray) {
					RemoteApplicationList.getInstance().addMessage(
							applicationDto);
				}
			}
		}
	}
}
